package com.clps.digital.service.impl;

import com.clps.digital.dao.CurrencyDao;
import com.clps.digital.dao.WealthManagementDao;
import com.clps.digital.model.dto.wealthManagement.WealthManagementRequest;
import com.clps.digital.model.entity.Currency;
import com.clps.digital.model.entity.WealthManagement;
import com.clps.digital.service.WealthManagementService;
import com.clps.digital.util.UserContext;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * @Author: 小炎子
 * @Date: 2024/9/3 下午3:57
 * @Description: 理财服务实现类
 **/
public class WealthManagementServiceImpl implements WealthManagementService {

    private WealthManagementDao wealthManagementDao;

    private CurrencyDao currencyDao;

    /*
    * @Author 小炎子
    * @Description 根据理财天数计算利率并返回
    * @Date 下午4:43 2024/9/3
    */
    @Override
    public BigDecimal save(WealthManagementRequest wealthManagementRequest) {
        LocalDateTime dateTime = LocalDateTime.now().plusDays(wealthManagementRequest.getDay());
        Long userId = UserContext.getUser();
        Currency currency = currencyDao.getCurrencyById(wealthManagementRequest.getCurrencyId());
        BigDecimal bigDecimalday = new BigDecimal(wealthManagementRequest.getDay());
        BigDecimal rate = currency.getRate().multiply(bigDecimalday.divide(new BigDecimal(365),5,BigDecimal.ROUND_HALF_UP));
        WealthManagement wealthManagement = new WealthManagement();
        wealthManagement.setCurrencyId(wealthManagementRequest.getCurrencyId());
        wealthManagement.setUserId(userId);
        wealthManagement.setRate(rate);

        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = dateTime.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());

        wealthManagement.setExpirationTime(date);
        wealthManagementDao.save(wealthManagement);
        return rate;
    }
}
